package zhanglinwei.cryptotools.core.source;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.PropertySource;
import zhanglinwei.cryptotools.core.resolver.CryptoablePropertyResolver;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheCryptoablePropertySource<T> extends PropertySource<T> implements CryptoablePropertySource<T> {
    private static final Logger log = LoggerFactory.getLogger(CacheCryptoablePropertySource.class);

    private final PropertySource<T> delegate;
    private final CryptoablePropertyResolver resolver;
    private final Map<String, Object> cache;

    public CacheCryptoablePropertySource(PropertySource<T> delegate, CryptoablePropertyResolver resolver) {
        super(delegate.getName(), delegate.getSource());
        this.delegate = delegate;
        this.resolver = resolver;
        this.cache = new ConcurrentHashMap<>();
    }

    @Override
    public PropertySource<T> getDelegate() {
        return delegate;
    }

    @Override
    public Object getProperty(String name) {
        if (cache.containsKey(name)) {
            return cache.get(name);
        }
        synchronized (this) {
            if (!cache.containsKey(name)) {
                Object resolved = resolveProperty(resolver, delegate, name);
                if (resolved != null) {
                    cache.put(name, resolved);
                }
            }
            return cache.get(name);
        }
    }

    @Override
    public void refresh() {
        cache.clear();
    }
}